<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="renderer" content="webkit">
  <!-- import CSS -->
  <link rel="stylesheet" href="/style/default/index.css">
  <link rel="stylesheet" href="/style/default/my.css">
  <style>
    .el-table .t0-row {
      background: #FFF8DC;
    }

    .el-table .t1-row {
      background: #F2F2F2;
    }

    .el-table .t2-row {
      background: #EEDFCC;
    }

    .el-table .t3-row {
      background: #E6E6FA;
    }

    .el-table .t4-row {
      background: #CDC8B1;
    }

    .el-table .t5-row {
      background: #F0F8FF;
    }

    .el-table .t6-row {
      background: #FAFAD2;
    }

    .el-table .t7-row {
      background: #F5FFFA;
    }

    .el-table .t8-row {
      background: #EEE9BF;
    }

    .el-table .t9-row {
      background: #F7F7F7;
    }
  </style>
</head>

<body style="background-color:#f8f8f8;">
  <div id="app">

    <!--添加角色-->
    <el-dialog title="添加角色" :visible.sync="dialogRoleVisible" :close-on-click-modal="false" width="50%">
      <div style="height:100px;overflow-y:auto;">
        <el-form ref="roleForm" :model="newRoleData" :rules="rules" label-width="120px" size="mini"
          style="margin-right: 30px;">
          <el-col :span="12">
            <el-form-item label="角色名" prop="name">
              <el-input v-model="newRoleData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="newRoleData.status" placeholder="请选择">
                <el-option v-for="item in optionData.status" :key="item.value" :label="item.name" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button @click="submitAddRole" type="primary">确 定
        </el-button>
      </div>
    </el-dialog>

    <!--添加/修改权限-->
    <el-dialog title="添加/修改权限" :visible.sync="dialogPowerVisible" :close-on-click-modal="false" width="50%">
      <div style="height:240px;overflow-y:auto;">
        <el-form ref="powerForm" :model="newPowerData" :rules="rules" label-width="120px" size="mini"
          style="margin-right: 30px;">
          <el-col :span="12">
            <el-form-item label="权限编号" prop="code">
              <el-input v-model.number="newPowerData.code"></el-input>
            </el-form-item>
            <el-form-item label="限制表" prop="controller">
              <el-input v-model="newPowerData.controller"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限简称" prop="name">
              <el-input v-model="newPowerData.name"></el-input>
            </el-form-item>
            <el-form-item label="方法" prop="method">
              <el-input v-model="newPowerData.method"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="newPowerData.ext" rows="5"></el-input>
            </el-form-item>
          </el-col>

        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPowerVisible = false">取 消</el-button>
        <el-button @click="submitAddPower" type="primary">确 定
        </el-button>
      </div>
    </el-dialog>


    <el-row :gutter="2" style="width: 100%">
      <el-col :span="8">
        <el-card class="box-card" :body-style="{padding:'10px'}">
          <div class="clearfix" style="padding: 6px;border-bottom:1px solid #eee;margin-bottom: 10px;">
            <span>角色名称</span>

            <div style="float: right;">
              <el-button-group>
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="showAddRoleDialog">添加</el-button>
              </el-button-group>
            </div>
          </div>
          <div>
            <el-table v-loading="roleLoading" ref="singleTable" highlight-current-row :data="roleData"
              style="width: 100%;" :cell-style="{padding:'5px'}" border :height="tableHeight" :max-height="tableHeight" size="mini"
              @current-change="selectRoleRow" @row-dblclick="showEditRoleDialog">

              <el-table-column prop="id" label="ID" width="50">
              </el-table-column>
              <el-table-column prop="name" label="角色名">
              </el-table-column>
              <el-table-column prop="status" label="状态" width="80">
                <template slot-scope="scope">
                  <span v-for="item in optionData.status" v-if="scope.row.status === item.value" :style="{color:item.color}">{{item.name}}</span>
                </template>
              </el-table-column>

            </el-table>

          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="box-card" :body-style="{padding:'10px'}">
          <div class="clearfix" style="padding: 6px;border-bottom:1px solid #eee;margin-bottom: 10px;height:26px;">
            <span class="title-group-align">权限列表</span>

            <div class="btn-group-align">
              <el-button-group>
                <el-button type="primary" size="mini" icon="el-icon-receiving" @click="submitEditRolePower">保存</el-button>
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="showAddPowerDialog">添加</el-button>
              </el-button-group>
            </div>
          </div>
          <div>
            <el-table v-loading="powerLoading" ref="multipleTable" :data="powerData" tooltip-effect="dark"
              style="width: 100%" :cell-style="{padding:'5px'}" :row-class-name="tableRowClassName" :height="tableHeight" :max-height="tableHeight"
              size="mini" @selection-change="selectionPowerChange" :default-sort = "{prop: 'code', order: 'ascending'}" @row-dblclick="showEditPowerDialog">
              <el-table-column type="selection" width="55" >
              </el-table-column>
              <el-table-column prop="code" label="编号" width="70">
              </el-table-column>
              <el-table-column prop="name" label="简称" width="160">
              </el-table-column>
              <el-table-column prop="controller" label="限制表" width="140">
              </el-table-column>
              <el-table-column prop="method" label="方法" width="140">
              </el-table-column>
              <el-table-column prop="ext" label="备注" show-overflow-tooltip>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>


  </div>
</body>
<script src="http://cdn.staticfile.org/vue/2.6.10/vue.min.js"></script>
<script src="http://cdn.staticfile.org/element-ui/2.12.0/index.js"></script>
<script src="http://cdn.staticfile.org/axios/0.19.0/axios.min.js"></script>
<script src="/js/validate.js"></script>
<script src="/js/my_util.js"></script>

<script>
  var marginHeight = 91; // 高差数

  var vm = new Vue({
    el: '#app',
    data: function () {
      return {
        tableHeight: window.innerHeight - marginHeight, // 表格高，当窗口改变大小的时候通过 pageResize 修改该值
        roleLoading: true,        // 是否显示加载角色数据加载中画面
        roleData: [],             // 角色数据
        currentRoleRow: null,     // 当前选中的角色
        powerLoading: true,       // 是否显示权限数据加载中画面
        powerData: [],            // 权限数据
        checkedPowerValues: [],   // 选中的权限数据列表
        dialogRoleVisible: false, // 是否显示角色信息对话框
        newRoleData: {},          // 新建的角色数据
        dialogPowerVisible: false,// 是否显示权限信息对话框
        newPowerData: {},         // 新建权限的数据

        // 表单数据验证
        rules: {
          name: [
            { required: true, trigger: 'blur', message: '该值不能为空' },
            { min: 2, max: 10, trigger: 'blur', message: '长度在 2 到 10 个字符' }
          ],
          code: [
            { required: true, min: 10000, max: 99999, trigger: 'blur', validator: validInteger } // 判断是否整数（必填）
          ],
          controller: [
            { required: true, trigger: 'blur', message: '该值不能为空' },
            { min: 2, max: 30, trigger: 'blur', message: '长度在 2 到 30 个字符' }
          ],
          method: [
            { required: true, trigger: 'blur', message: '该值不能为空' },
            { min: 2, max: 16, trigger: 'blur', message: '长度在 2 到 16 个字符' }
          ],
        },
      }
    },
    computed: {
      // 从缓存中读取
      optionData: function () {
        var optionDataStr = sessionStorage.getItem('optionData');
        return JSON.parse(optionDataStr || "{}");
      }
    },
    mounted() {
      // 当窗口大小发生改变的时候系统自动调用
      window.onresize = () => {
        this.pageResize();
      }
    },
    methods: {
      // 改变表格高度
      pageResize() {
        this.tableHeight = window.innerHeight - marginHeight;
      },

      // 表格绘制过程中自动回调，用于设置行背景色
      tableRowClassName({ row, rowIndex }) {
        let v = Math.trunc(row.code / 10000);
        return 't' + v + '-row';
      },

      // 显示添加角色的对话框
      showAddRoleDialog(){
        this.newRoleData = {status:1};
        this.dialogRoleVisible = true;
      },

      showEditRoleDialog(row){
        this.newRoleData = JSON.parse(JSON.stringify(row));
        this.dialogRoleVisible = true;
      },

      // 显示添加权限的对话框
      showAddPowerDialog(){
        this.newPowerData = {status:1};
        this.dialogPowerVisible = true;
      },

      // 显示修改权限的对话框
      showEditPowerDialog(row){
        this.newPowerData = JSON.parse(JSON.stringify(row));
        this.dialogPowerVisible = true;
      },

      // 选择角色，同步该角色对应的权限列表
      selectRoleRow(row) {
        if(row != null) {
          this.currentRoleRow = row;
          let rows = [];

          // 遍历权限列表，把存在 powerList 中的权限添加到 rows 列表中
          this.powerData.forEach(item => {
            if (row.power_list.indexOf(item.code) > -1) {
              rows.push(item);
            }
          });
          this.$refs.multipleTable.clearSelection(); // 清空选中项

          // 遍历 rows 项，把对应的权限select状态设为“选中”
          rows.forEach(i => {
            this.$refs.multipleTable.toggleRowSelection(i, true);
          });
        }
      },

      // 当权限列表多选框发生改变的时候自动调用
      selectionPowerChange(val) {

        this.checkedPowerValues = val;
        let powerList = [];

        // 遍历选中的权限项 val ，把对应权限的 code 存入 powerList 中
        this.checkedPowerValues.forEach(item => {
          powerList.push(item.code);
        });

        if(this.currentRoleRow){
          this.currentRoleRow.power_list = powerList;
        }
      },

      // 提交新建角色
      submitAddRole(e) {
        this.$refs.roleForm.validate((valid) => {
          if (valid) {

            // 把数组转成字符串
            this.newRoleData.power_list = arrayToStr(this.newRoleData.power_list, ",");

            axios.post('/admin/base/edit/sys_role.bu', this.newRoleData)
              .then(function (response) {
                if (response.data.code > 0) {
                  vm.$message.success(response.data.msg);
                  vm.dialogRoleVisible = false;
                  loadRoleData()
                } else {
                  vm.$message.error(response.data.msg);
                }
              })
              .catch(function (error) {
                vm.$message.error('出错：' + error);
              });
          } else {
            vm.$message.error('错误：提交失败，请检查表单数据是否符合要求！');
            return false;
          }
        });
      },

      // 提交新建权限
      submitAddPower(e) {

        this.$refs.powerForm.validate((valid) => {
          if (valid) {
            axios.post('/admin/base/edit/sys_power.bu', this.newPowerData)
              .then(function (response) {
                if (response.data.code > 0) {
                  vm.$message.success(response.data.msg);
                  vm.dialogPowerVisible = false;

                  // 刷新数据
                  loadPowerData()
                  loadRoleData();

                } else {
                  vm.$message.error(response.data.msg);
                }
              })
              .catch(function (error) {
                vm.$message.error('出错：' + error);
              });
          } else {
            vm.$message.error('错误：提交失败，请检查表单数据是否符合要求！');
            return false;
          }
        });
      },

      // 提交对角色权限项的修改 
      submitEditRolePower(e) {

        // 把权限roles字符串转成int数组
        this.roleData.forEach(item => {
          item.power_list = arrayToStr(item.power_list);
        });

        axios.post('/admin/sys/edit/sys_role!save_all.bu', this.roleData)
          .then(function (response) {
            if (response.data.code > 0) {
              vm.$message.success(response.data.msg);
            } else {
              vm.$message.error(response.data.msg);
            }
          })
          .catch(function (error) {
            vm.$message.error('出错：' + error);
          });
      }

    },
  });


  // 读取角色和权限数据等
  function loadRoleData() {
    // 获取角色数据
    axios.get('/admin/base/show/sys_role!all.bu')
      .then(function (response) {
        if (response.data.code > 0) {

          // 把权限roles字符串转成int数组
          response.data.bundle.forEach(item => {
            item.power_list = strToIntArray(item.power_list);
          });

          vm.roleData = response.data.bundle;
          vm.roleLoading = false;
        } else if (response.data.code == 0) {
          vm.$message.error("没有数据");
          vm.roleLoading = false;
        } else {
          vm.$message.error(response.data.msg);
        }
      })
      .catch(function (error) {
        vm.$message.error('获取数据失败！' + error);
      });
  };

  // 读取角色和权限数据等
  function loadPowerData() {
    // 获取权限数据
    axios.get('/admin/base/show/sys_power!all.bu')
      .then(function (response) {
        if (response.data.code > 0) {
          vm.powerData = response.data.bundle;
          vm.powerLoading = false;
        } else if (response.data.code == 0) {
          vm.$message.error("没有数据");
          vm.powerLoading = false;
        } else {
          vm.$message.error(response.data.msg);
        }
      })
      .catch(function (error) {
        vm.$message.error('获取数据失败！' + error);
      });
  };

  loadRoleData();
  loadPowerData();


</script>

</html>